﻿
//********************* Controls, Required Fields Enabled, Regular Expression Validation and Validation Messages are here ***********************

var idControlArray = new Array("txtFirstName", "txtLastName", "txtAddress1", "txtAddress2", "txtCity", "ddlState", "ddlPhoneType", "txtZip", "txtPhone", "txtEmailPersonal", "txtPassword1", "txtPassword2", "txtDOBPersonal");

var initialValueArray = new Array("First Name", "Last Name", "Address 1", "Address 2 (Optional)", "City", "State", "", "Zip", "Phone Number", "Email", "Password for Your Account", "Re-enter password", "DOB: MM/DD/YYYY");

var requiredArray = new Array("Yes", "Yes", "Yes", "No", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes");

var regularExpressionRequiredArray = new Array("Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "Yes");

var requiredMessageArray = new Array(
    "First Name required\n",
    "Last Name required\n",
    "Address required\n",
    "",
    "City required\n",
    "State required\n",
    "Phone Type required\n",
    "Required\n",
    "Phone number required\n",
    "Email address required\n",
    "Password required\n",
    "Please confirm password\n",
    "Date of birth required\n");

var regularExpressionArray = new Array(
    /^[A-Za-z 0-9 \- _ . ']+$/,
    /^[A-Za-z 0-9 \- _ . ']+$/,
    /^[A-Za-z 0-9 \- , #. ( )']+$/,
    /^[A-Za-z 0-9 \- , #. ( ) ']+$/,
    /^[A-Za-z 0-9 \- _ . ']+$/,
    /^[A-Za-z 0-9 \- _ . ']+$/,
    /^[A-Za-z 0-9 \- _ . ']+$/,
    /^\d{5}$|^\d{5}-\d{4}$/,
    /^[A-Za-z 0-9 \- _ . ' ( )]+$/,
    /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
    /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}$/,
    /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}$/,
    /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);

var regularExpressionMessageArray = new Array(
    "Invalid first name.\n",
    "Invalid last name.\n",
    "Invalid address.\n",
    "Invalid address.\n",
    "Invalid city.\n",
    "Invalid state.\n",
    "Invalid phone type.\n",
    "Invalid zip code.\n",
    "Invalid phone number.\n",
    "Invalid email format.\n",
    "Invalid Password.\n",
    "Invalid Password.\n",
    "Invalid Date of birth\n");

//********************* Regular Expressions are here ***********************

var isValidationSuccess;
var message = '';
var prospectData;
var globalErrorMessage = '';

//$(window).on("resize", function () {
//    $.fn.colorbox.resize({
//        height: "90%",
//        width: "92%"
//    });
//});

$(document).ready(function () {

    /***************** This portion is for responsive validation message change on text change of a TextBox */


    $("input[type=text],input[type=select],input[type=email],input[type=tel]").on("blur", function () {

        if ($(this).attr('id') == "txtAddress2" && $(this).val().trim() != '') {
            regularExpressionRequiredArray[3] = "Yes";
            RequiredFieldValidation(true, $(this).attr('id'));
        }
        else if ($(this).attr('id') == "txtAddress2" && $(this).val().trim() == '') {
            regularExpressionRequiredArray[3] = "No";
            RequiredFieldValidation(true, $(this).attr('id'));
            HideCommonRequiredMessage($("#" + $(this).attr('id')), "");
        }
        if ($(this).val().trim() != '') {
            RequiredFieldValidation(true, $(this).attr('id'));
        }
        // Added At Last - 01-10-2014 
        if ($(this).val().trim() == '') {
            RequiredFieldValidation(true, $(this).attr('id'));
        }
    });

    $('#ddlState').change(function () {

        RequiredFieldValidation(true, $(this).attr('id'));
    });
    $('#ddlPhoneType').change(function () {

        RequiredFieldValidation(true, $(this).attr('id'));
    });
});

function SavePersonalInformation() {

    globalErrorMessage = '';
    if (DoValidation()) {
        PostUserData();
    }
    //$('.yourInfo').hide();
    //$('.careRecipient').show();
    return false;
}

function PostUserData() {

    params = BindParamsData();

    $.ajax({
        type: "POST",
        url: "Web_Service/Enroll-PersonalInfo.asmx/SubmitPersonalInfo",
        contentType: "application/json; charset=utf-8",
        data: params,
        async: false,
        dataType: "json",
        beforeSend: function () { $('.submitPersonalInfo').attr("disabled", "disabled"); },
        complete: function () { $('.submitPersonalInfo').removeAttr("disabled"); },
        success: function (data) {

            if (data != null || data != undefined) {
                if (data.d == "Created") {
                    $('.yourInfo').hide();
                    $('.careRecipient').show();

                    $('#spanYourInfo').addClass('steps-completed');
                    $('#spanYourInfo').removeClass('pointy-small-active');
                    $('#spanYourInfo').next('a').removeClass('vertical-nav-active');

                    $('#spanCareReceipient').addClass('pointy-small-active-active');
                    $('#spanCareReceipient').css('display', 'block');
                    $('#spanCareReceipient').next('a').addClass('vertical-nav-active');
                }
                if (data.d == "Updated") {
                    $.colorbox({ href: 'public/retunrning-users.aspx', iframe: true, innerWidth: 320, innerHeight: 401 });
                }
                if (data.d == "StepsCompleted") {
                    //alert('<p class="alert alert-error">You are already registered within the CaregiverHQ system. Please click the Sign-In button in the upper-right and use your credential to log-in and edit your information.</p>');
                    $('#modalAlreadyRegistered').modal('show');
                    $('#aUserSignIn').trigger('click');
                }
            }

        },
        error: function (data, message) {
            //$('.please_fix').css('display', 'block');
            //$('.please_fix').html(message);
        }
    });

}

function BindParamsData() {

    var allParam = '{';

    allParam += "'firstName':'" + EmptyIfUn($("#txtFirstName").val().trim()) + "',";
    allParam += "'lastName':'" + EmptyIfUn($("#txtLastName").val().trim()) + "',";
    allParam += "'address1':'" + EmptyIfUn($("#txtAddress1").val().trim()) + "',";
    allParam += "'address2':'" + EmptyIfUn($("#txtAddress2").val().trim()) + "',";
    allParam += "'dateOfBirth':'" + $("#txtDOBPersonal").val().trim() + "',";
    allParam += "'city':'" + $("#txtCity").val().trim() + "',";
    allParam += "'state':'" + $("#ddlState option:selected").val() + "',";
    allParam += "'zip':'" + $("#txtZip").val().trim() + "',";
    allParam += "'phone':'" + $("#txtPhone").val().trim() + "',";
    allParam += "'phoneType':'" + $("#ddlPhoneType option:selected").val() + "',";
    allParam += "'email':'" + $("#txtEmailPersonal").val().trim() + "',";
    allParam += "'password':'" + $("#txtPassword1").val().trim() + "',";
    if ($('#cbxisBillingAddress').is(":checked")) {
        allParam += "'isBillingAddress':'true',";
    } else {
        allParam += "'isBillingAddress':'false',";
    }
    if ($('#cbxisOptOut').is(":checked")) {
        allParam += "'isOptOut':'true'";
    } else {
        allParam += "'isOptOut':'false'";
    }

    allParam += "}";

    return allParam;
}

function EmptyIfUn(val) {

    if (typeof val === "undefined" || val == "Address 2 (Optional)") {
        return "";
    }
    else {
        var retValue = new String(val);
        return retValue.replace(/'/g, "\\'");
    }
}

function ReturnEmptyValue() {
    return null;
}

//==== Input Validation Area ===========================================

function DoValidation() {

    isValidationSuccess = true;

    RequiredFieldValidation(false, null);

    if (!isValidationSuccess) {
        return false;
    } else {
        if ($('#txtPassword1').val() == $('#txtPassword2').val()) {

            $('#txtPassword1').removeClass('red-error-box');
            $('#txtPassword2').removeClass('red-error-box');

            $('#spanPasswordDoNotMatch').text('');
            $('#spanPasswordDoNotMatch').removeClass('required-text');
            $('#spanPasswordDoNotMatch').hide();
            if ($('#cbxTermsandConditions').is(":checked")) {

                $('#spanTermsandConditions').removeClass('required-text');
                $('#spanTermsandConditions').hide();
                $('#spanTermsandConditions').text('');

                $('#cbxTermsandConditions').parent('span').removeClass('red-error-checkbox');

                return true;
            } else {

                globalErrorMessage = globalErrorMessage + "Please Accept the Terms and Conditions.\n";

                $('#spanTermsandConditions').text('Please Accept the Terms and Conditions.');
                $('#spanTermsandConditions').show();
                $('#spanTermsandConditions').addClass('required-text');

                $('#cbxTermsandConditions').parent('span').addClass('red-error-checkbox');

                return false;
            }
        }
        else {

            globalErrorMessage = globalErrorMessage + "Passwords do not match.\n";
            $('#spanPasswordDoNotMatch').text('Passwords do not match');
            $('#spanPasswordDoNotMatch').show();
            $('#spanPasswordDoNotMatch').addClass('required-text');
            $('#txtPassword1').addClass('red-error-box');
            $('#txtPassword2').addClass('red-error-box');
            return false;
        }
    }
}


//**************** All Required Field Validations are Here ************************************

function RequiredFieldValidation(isSingleValidation, controlId) {

    var validationMessage = '';
    var isRequiredFieldEnabled = false;
    var isRegularExpressionValid = false;
    var value = null;
    var length = idControlArray.length;
    var counter = 0;
    if (isSingleValidation) {
        for (counter = 0; counter < length; counter++) {
            if (idControlArray[counter] == controlId) {
                length = counter + 1;
                break;
            }
        }
    }

    for (counter = counter; counter < length; counter++) {

        if ($("#" + idControlArray[counter]).is("input"))
            value = $("#" + idControlArray[counter]).val().trim();

        if ($("#" + idControlArray[counter]).is("select" + "#" + idControlArray[counter]))
            value = $("#" + idControlArray[counter] + " option:selected").val();

        if (requiredArray[counter] == "Yes") {
            if (value == undefined || value == "" || value == "null" || value == initialValueArray[counter]) {
                isRequiredFieldEnabled = true;
                ShowCommonRequiredMessage($("#" + idControlArray[counter]), requiredMessageArray[counter]);
                validationMessage = "required-text Occured";
            }
            else {
                isRequiredFieldEnabled = false;
                HideCommonRequiredMessage($("#" + idControlArray[counter]), "");
            }
        }

        if (regularExpressionRequiredArray[counter] == "Yes") {
            isRegularExpressionValid = RegularExpressionValidation($("#" + idControlArray[counter]), value, regularExpressionArray[counter]);
            if (!isRequiredFieldEnabled) {
                if (!isRegularExpressionValid) {
                    ShowCommonRegularExpressionMessage($("#" + idControlArray[counter]), regularExpressionMessageArray[counter]);
                    validationMessage = "Regular Expression required-text Occured";
                } else {
                    HideCommonRegularExpressionMessage($("#" + idControlArray[counter]), "");
                }
            }
        }
    }
    if (validationMessage == '') {
        isValidationSuccess = true;
    }
    else {
        isValidationSuccess = false;
    }
}

//=============================== END =======================================================================================

//=================== Section For Displaying All Kind of required-text Messages =====================================================

function ShowCommonRequiredMessage(control, message) {

    // globalErrorMessage = globalErrorMessage + message;
    control.next('span').css('display', 'block');
    control.next('span').addClass('required-text');
    control.next('span').text(message);
}

function HideCommonRequiredMessage(control, message) {

    //globalErrorMessage = globalErrorMessage.replace(message, '');
    control.next('span').css('display', 'none');
    control.next('span').removeClass('required-text');
    control.next('span').text(message);
}

function ShowCommonRegularExpressionMessage(control, message) {

    //globalErrorMessage = globalErrorMessage + message;
    control.next('span').css('display', 'block');
    control.next('span').addClass('required-text');
    control.next('span').text(message);

}

function HideCommonRegularExpressionMessage(control, message) {

    //globalErrorMessage = globalErrorMessage.replace(message, '');
    control.next('span').css('display', 'none');
    control.next('span').removeClass('required-text');
    control.next('span').text(message);

}

//=============================== END =======================================================================================


//=========================================== Custom Logic Goes Here ========================================================

function RegularExpressionValidation(control, valueToMatch, regExpression) {

    if (valueToMatch == null || valueToMatch.trim() == "") {
        return true;
    }

    if (!regExpression.test(valueToMatch)) {
        return false;
    }

    if (control.attr('id') == "txtDOBPersonal" && !isDateCareGiver(valueToMatch, "/", 1, 0, 2)) {
        return false;
    }
    return true;
}

function CheckAndReturn(elem) {
    return $(elem).val().trim();
}

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

function clearTextHere(field, initialText) {

    if (field != null) {
        if (field.value == initialText) {
            field.value = "";
            if (initialText == "Phone Number") {
                $("#txtPhone").mask("999-999-9999");
                $("#txtScheduleRequestPhone").mask("999-999-9999");
            }
            if (initialText == "DOB: MM/DD/YYYY") {
                $("#txtDOBCareReceipent").mask("99/99/9999");

            }

        }
    }
}

function clearTextHere2(field, initialText) {
    if (field != null) {
        if (field.value == initialText) {
            field.value = "";
            $("#txtDOBCareReceipent2").mask("99/99/9999");

        }
    }
}


function resetText(field, initialText) {

    if (field.value == "") {
        field.value = initialText;
        if (initialText == "Password for Your Account") {
            $("#txtPassword1").attr("type", "text");
        }
        if (initialText == "Re-enter password") {
            $("#txtPassword2").attr("type", "text");
        }
        if (initialText == "Phone Number") {
            $("#txtPhone").unmask("999-999-9999");
            $("#txtScheduleRequestPhone").unmask("999-999-9999");
        }

    }

    if (field.value == "__/__/____") {


        $("#txtDOBCareReceipent").unmask("99/99/9999");

        field.value = initialText;
    }

    if (field.value == "___-___-____") {

        $("#txtPhone").unmask("999-999-9999");
        field.value = initialText;
    }
}

function resetText2(field, initialText) {
    if (field.value == "__/__/____") {

        $("#txtDOBCareReceipent2").unmask("99/99/9999");

        field.value = initialText;
    }
}




$.date = function (dateObject) {

    dateObject = dateObject.split(' ')[0];
    var d = new Date(dateObject);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }
    var date = day + "/" + month + "/" + year;

    return date;
};

//**************** End ************************************

function isDateCareGiver(value, sepVal, dayIdx, monthIdx, yearIdx) {
    try {
        //Change the below values to determine which format of date you wish to check. It is set to dd/mm/yyyy by default.
        var DayIndex = dayIdx !== undefined ? dayIdx : 0;
        var MonthIndex = monthIdx !== undefined ? monthIdx : 0;
        var YearIndex = yearIdx !== undefined ? yearIdx : 0;

        value = value.replace(/-/g, "/").replace(/\./g, "/");
        var SplitValue = value.split(sepVal || "/");
        var OK = true;
        if (!(SplitValue[DayIndex].length == 1 || SplitValue[DayIndex].length == 2)) {
            OK = false;
        }
        if (OK && !(SplitValue[MonthIndex].length == 1 || SplitValue[MonthIndex].length == 2)) {
            OK = false;
        }
        if (OK && SplitValue[YearIndex].length != 4) {
            OK = false;
        }
        if (OK) {
            var Day = parseInt(SplitValue[DayIndex], 10);
            var Month = parseInt(SplitValue[MonthIndex], 10);
            var Year = parseInt(SplitValue[YearIndex], 10);

            if (OK = ((Year > 1900) && (Year <= new Date().getFullYear()))) {
                if (OK = (Month <= 12 && Month > 0)) {

                    var LeapYear = (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0));

                    if (OK = Day > 0) {
                        if (Month == 2) {
                            OK = LeapYear ? Day <= 29 : Day <= 28;
                        }
                        else {
                            if ((Month == 4) || (Month == 6) || (Month == 9) || (Month == 11)) {
                                OK = Day <= 30;
                            }
                            else {
                                OK = Day <= 31;
                            }
                        }
                    }
                }
            }
        }
        return OK;
    }
    catch (e) {
        return false;
    }
}